package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.AlertDataDto;
import com.zzyl.nursing.dto.AlertDataQueryDTO;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.vo.AlertDataVo;
import com.zzyl.serve.service.INursingElderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 报警数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-28
 */
@Slf4j
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private INursingElderService nursingElderService;

    @Autowired
    private IElderService elderService;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        return alertDataMapper.selectAlertDataList(alertData);
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return save(alertData) ? 1 : 0;
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return updateById(alertData) ? 1 : 0;
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 分页查询报警数据
     *
     * @param dto
     */
    @Override
    public List<AlertDataVo> pageList(AlertDataQueryDTO dto) {
        //前置校验,获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();

        //构建查询条件
        LambdaQueryWrapper<AlertData> queryWrapper = new LambdaQueryWrapper<>();

        //添加基础查询条件
        queryWrapper.eq(dto.getStatus() != null, AlertData::getStatus, dto.getStatus())
                .eq(StringUtils.isNotBlank(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
                .between(dto.getStartTime() != null && dto.getEndTime() != null,
                        AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime());

        //添加数据权限控制
        if (!Constants.USER_ADMIN.equals(userId)) {
            // 查询当前护理员负责的所有老人ID
            List<Long> elderIds = nursingElderService.getElderIdByUserId(userId);
            if (CollectionUtils.isEmpty(elderIds)) {
                log.info("当前护理员没有负责的老人");
                return Collections.emptyList();
            }
            // 过滤报警数据
            queryWrapper.eq(AlertData::getUserId,userId);
        }

        //执行分页查询
        Page<AlertData> page = this.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);


        //数据库实体转换为视图对象
        List<AlertDataVo> voList = new ArrayList<>();
        for (AlertData alertData : page.getRecords()) {
            AlertDataVo vo = new AlertDataVo();
            Long accessLocation = Long.valueOf(alertData.getAccessLocation());
            Elder elder = elderService.selectElderById(accessLocation);
            if (elder == null) {
                log.error("老人为空");
                continue;
            }
            alertData.setAccessLocation(elder.getName());
            BeanUtils.copyProperties(alertData, vo);
            //复制实体属性到VO
            voList.add(vo);
        }

        //返回转换后的VO列表
        return voList;
    }

    /**
     * 添加数据权限控制
     * 如果用户ID为1可以查看所有数据，其他用户只能查看自己的数据
     */
    private void addDataPermission(Long userId, LambdaQueryWrapper<AlertData> queryWrapper) {


    }


    /**
     * 处理设备报警数据
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleAlertData(AlertDataDto dto) {
        // 报警数据id校验
        if (dto.getId() == null) {
            throw new BaseException("报警数据id不能为空");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("当前用户未登录或登录信息异常，无法处理报警数据");
        }
        String username = loginUser.getUsername();
        Long userId = loginUser.getUserId();

        // 先根据ID查询当前记录，获取设备信息
        AlertData currentAlert = this.getById(dto.getId());
        if (currentAlert == null) {
            throw new BaseException("报警数据不存在");
        }

        // 根据相同的设备信息更新所有相关记录
        this.lambdaUpdate()
                // 使用设备标识作为条件，更新所有相同设备的记录
                .eq(AlertData::getIotId, currentAlert.getIotId())
                .eq(AlertData::getDeviceName, currentAlert.getDeviceName())
                .eq(AlertData::getNickname, currentAlert.getNickname())
                .eq(AlertData::getCreateTime, currentAlert.getCreateTime())
                // 只更新未处理的记录（可选，根据业务需求）
                .eq(AlertData::getStatus, 0)
                // 记录处理结果
                .set(AlertData::getProcessingResult, dto.getProcessingResult())
                // 记录处理时间
                .set(AlertData::getProcessingTime, LocalDateTime.now())
                // 记录处理人
                .set(AlertData::getProcessorName, username)
                .set(AlertData::getProcessorId, userId)
                .set(AlertData::getStatus, 1)
                .update();

    }
}
